/**
 * 
 */
package org.meruvian.yama.service.impl;

import org.meruvian.yama.dao.UserDao;
import org.meruvian.yama.entity.Person;
import org.meruvian.yama.entity.User;
import org.meruvian.yama.service.PersonService;
import org.meruvian.yama.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Dian Aditya
 * 
 */
@Service
@Transactional(readOnly = true)
public class UserServiceImpl implements UserService {

	@Autowired
	private PersonService personService;
	@Autowired
	private UserDao userDao;

	@Transactional
	public void save(User user) {
		if(user.getId()==null){
			user.setId("");
		}
		User temp = userDao.findById(user.getId());

		if (temp == null) {
			Person person = user.getPerson();
//			person.setId("");
			personService.save(person);
			
			user.setPerson(person);
			user.setId(null);
			user.setSecret(null);
			userDao.save(user);
		} else {
			temp.setPassword(user.getPassword());
			temp.setUsername(user.getUsername());
			temp.setSecret(user.getSecret());
			temp.setPerson(user.getPerson());

			userDao.save(temp);
		}

	}

	@Transactional(readOnly = true)
	public User getBySecret(String secret) {
		return userDao.getBySecret(secret);
	}

	@Transactional(readOnly = true)
	public User getByUserPassword(String username, String password) {
		return userDao.getByUserPassword(username, password);
	}

}
